import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.Set;
import java.util.Iterator;

public class Server {
    public static void main(String[] args) throws IOException {
        // 打开一个通道，用于接收客户端连接请求
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 绑定到端口8080
        serverSocketChannel.socket().bind(new InetSocketAddress("0.0.0.0", 8080));
        // 创建选择器，用于监控多个通道的I/O操作
        Selector selector = Selector.open();
        // 将服务器套接字通道注册到选择器上，监听新的连接请求
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("Server started on port 8080");

        while (true) {
            // 阻塞当前线程，直到某个通道要有新的i/o操作
            selector.select();
            // 获取所有已经准备好进行i/o操作的对象
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            // 用于处理这些对象
            Iterator<SelectionKey> iterator = selectedKeys.iterator();

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    // 新的连接请求到达
                    SocketChannel client = serverSocketChannel.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                    System.out.println("New client connected: " + client.getRemoteAddress());
                } else if (key.isReadable()) {
                    // 处理读取操作
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    try {
                        int bytesRead = client.read(buffer);
                        if (bytesRead == -1) {
                            // 客户端关闭连接
                            client.close();
                            System.out.println("Client disconnected: " + client.getRemoteAddress());
                        } else if (bytesRead > 0) {
                            // 处理接收到的数据
                            buffer.flip();
                            String request = new String(buffer.array(), 0, bytesRead);
                            System.out.println("Received request: " + request);

                            // 构建HTTP响应
                            String responseContent = "<html><body><h1>Hello, World!</h1></body></html>";
                            String response = "HTTP/1.1 200 OK\r\n" +
                                              "Content-Type: text/html\r\n" +
                                              "Content-Length: " + responseContent.length() + "\r\n" +
                                            //   "Connection: close\r\n" +
                                              "\r\n" +
                                              responseContent;

                            // 将响应写回到客户端
                            ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
                            while (responseBuffer.hasRemaining()) {
                                client.write(responseBuffer);
                            }
                        }
                    } catch (IOException e) {
                        // 处理连接重置等异常情况
                        System.err.println("Error reading from client: " + e.getMessage());
                        client.close();
                    }
                }
            }
        }
    }
}